/**
 * 简单的Mock API服务器
 * 用于测试内容渲染功能
 */

const http = require('http');
const url = require('url');
const querystring = require('querystring');

const PORT = 8081;

// 模拟数据存储
let items = [];
let nextId = 1;

/**
 * 生成响应格式
 * @param {*} data - 响应数据
 * @param {string} message - 响应消息
 * @param {number} code - 响应码
 * @returns {object} 标准响应格式
 */
const createResponse = (data = null, message = 'success', code = 200) => {
  return {
    code,
    message,
    data,
    timestamp: new Date().toISOString()
  };
};

/**
 * 设置CORS头
 * @param {object} res - 响应对象
 */
const setCorsHeaders = (res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
};

/**
 * 发送JSON响应
 * @param {object} res - 响应对象
 * @param {object} data - 响应数据
 * @param {number} statusCode - HTTP状态码
 */
const sendJsonResponse = (res, data, statusCode = 200) => {
  setCorsHeaders(res);
  res.statusCode = statusCode;
  res.end(JSON.stringify(data, null, 2));
};

/**
 * 获取请求体数据
 * @param {object} req - 请求对象
 * @returns {Promise<object>} 解析后的请求体
 */
const getRequestBody = (req) => {
  return new Promise((resolve, reject) => {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const data = body ? JSON.parse(body) : {};
        resolve(data);
      } catch (error) {
        reject(error);
      }
    });
    req.on('error', reject);
  });
};

/**
 * 路由处理器
 */
const routeHandlers = {
  // 健康检查
  'GET /api/v1/health': (req, res, parsedUrl) => {
    const response = createResponse({
      status: 'ok',
      timestamp: new Date().toISOString(),
      itemsCount: items.length
    }, '服务正常');
    sendJsonResponse(res, response);
  },

  // 获取服务状态
  'GET /api/v1/status': (req, res, parsedUrl) => {
    const response = createResponse({
      server: 'Mock API Server',
      version: '1.0.0',
      itemsCount: items.length,
      uptime: process.uptime(),
      memory: process.memoryUsage()
    }, '状态正常');
    sendJsonResponse(res, response);
  },

  // 获取项目列表
  'GET /api/v1/items': (req, res, parsedUrl) => {
    const query = parsedUrl.query || {};
    const page = parseInt(query.page) || 1;
    const limit = parseInt(query.limit) || 10;
    const category_id = query.category_id;
    
    let filteredItems = items;
    
    // 按分类过滤
    if (category_id) {
      filteredItems = items.filter(item => item.category_id == category_id);
    }
    
    // 分页
    const startIndex = (page - 1) * limit;
    const endIndex = startIndex + limit;
    const paginatedItems = filteredItems.slice(startIndex, endIndex);
    
    const result = {
      items: paginatedItems,
      total: filteredItems.length,
      page: page,
      limit: limit,
      totalPages: Math.ceil(filteredItems.length / limit)
    };
    
    console.log(`获取项目列表: 总数=${result.total}, 页码=${page}`);
    sendJsonResponse(res, createResponse(result, '获取成功'));
  },

  // 创建项目
  'POST /api/v1/items': async (req, res, parsedUrl) => {
    try {
      const body = await getRequestBody(req);
      const { name, content, content_type, category_id, description } = body;
      
      // 验证必填字段
      if (!name || !content) {
        return sendJsonResponse(res, createResponse(null, '名称和内容不能为空', 400), 400);
      }
      
      // 创建新项目
      const newItem = {
        id: nextId++,
        name,
        content,
        content_type: content_type || 'rich_text',
        category_id: category_id || 1,
        description: description || '',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      items.push(newItem);
      
      console.log(`创建项目成功: ID=${newItem.id}, 名称=${newItem.name}`);
      sendJsonResponse(res, createResponse(newItem, '创建成功'));
      
    } catch (error) {
      console.error('创建项目失败:', error);
      sendJsonResponse(res, createResponse(null, '创建失败', 500), 500);
    }
  }
};

/**
 * 处理动态路由（如 /api/v1/items/:id）
 * @param {string} method - HTTP方法
 * @param {string} pathname - 路径
 * @param {object} req - 请求对象
 * @param {object} res - 响应对象
 * @param {object} parsedUrl - 解析后的URL
 */
const handleDynamicRoute = async (method, pathname, req, res, parsedUrl) => {
  // 匹配 /api/v1/items/:id
  const itemIdMatch = pathname.match(/^\/api\/v1\/items\/(\d+)$/);
  
  if (itemIdMatch) {
    const id = parseInt(itemIdMatch[1]);
    
    if (method === 'GET') {
      // 获取项目详情
      const item = items.find(item => item.id === id);
      
      if (!item) {
        return sendJsonResponse(res, createResponse(null, '项目不存在', 404), 404);
      }
      
      console.log(`获取项目详情: ID=${id}, 名称=${item.name}`);
      sendJsonResponse(res, createResponse(item, '获取成功'));
      
    } else if (method === 'PUT') {
      // 更新项目
      try {
        const body = await getRequestBody(req);
        const itemIndex = items.findIndex(item => item.id === id);
        
        if (itemIndex === -1) {
          return sendJsonResponse(res, createResponse(null, '项目不存在', 404), 404);
        }
        
        // 更新项目
        const updatedItem = {
          ...items[itemIndex],
          ...body,
          id, // 确保ID不被覆盖
          updated_at: new Date().toISOString()
        };
        
        items[itemIndex] = updatedItem;
        
        console.log(`更新项目成功: ID=${id}, 名称=${updatedItem.name}`);
        sendJsonResponse(res, createResponse(updatedItem, '更新成功'));
        
      } catch (error) {
        console.error('更新项目失败:', error);
        sendJsonResponse(res, createResponse(null, '更新失败', 500), 500);
      }
      
    } else if (method === 'DELETE') {
      // 删除项目
      const itemIndex = items.findIndex(item => item.id === id);
      
      if (itemIndex === -1) {
        return sendJsonResponse(res, createResponse(null, '项目不存在', 404), 404);
      }
      
      const deletedItem = items.splice(itemIndex, 1)[0];
      
      console.log(`删除项目成功: ID=${id}, 名称=${deletedItem.name}`);
      sendJsonResponse(res, createResponse(null, '删除成功'));
    }
    
    return true; // 表示已处理
  }
  
  return false; // 表示未处理
};

// 创建HTTP服务器
const server = http.createServer(async (req, res) => {
  const parsedUrl = url.parse(req.url, true);
  const method = req.method;
  const pathname = parsedUrl.pathname;
  
  console.log(`[${new Date().toLocaleTimeString()}] ${method} ${pathname}`);
  
  // 处理OPTIONS请求（CORS预检）
  if (method === 'OPTIONS') {
    setCorsHeaders(res);
    res.statusCode = 200;
    res.end();
    return;
  }
  
  // 构建路由键
  const routeKey = `${method} ${pathname}`;
  
  // 检查静态路由
  if (routeHandlers[routeKey]) {
    routeHandlers[routeKey](req, res, parsedUrl);
    return;
  }
  
  // 检查动态路由
  const handled = await handleDynamicRoute(method, pathname, req, res, parsedUrl);
  if (handled) {
    return;
  }
  
  // 404处理
  sendJsonResponse(res, createResponse(null, '接口不存在', 404), 404);
});

// 启动服务器
server.listen(PORT, () => {
  console.log(`\n🚀 Mock API Server 启动成功!`);
  console.log(`📍 服务地址: http://localhost:${PORT}`);
  console.log(`🔍 健康检查: http://localhost:${PORT}/api/v1/health`);
  console.log(`📊 服务状态: http://localhost:${PORT}/api/v1/status`);
  console.log(`\n📝 可用接口:`);
  console.log(`   POST   /api/v1/items        - 创建项目`);
  console.log(`   GET    /api/v1/items        - 获取项目列表`);
  console.log(`   GET    /api/v1/items/:id    - 获取项目详情`);
  console.log(`   PUT    /api/v1/items/:id    - 更新项目`);
  console.log(`   DELETE /api/v1/items/:id    - 删除项目`);
  console.log(`\n等待请求中...\n`);
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n正在关闭服务器...');
  server.close(() => {
    process.exit(0);
  });
});

process.on('SIGTERM', () => {
  console.log('\n正在关闭服务器...');
  server.close(() => {
    process.exit(0);
  });
});